package com.shanzmoo.job.base;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.db.job.entity.ScheduleJobEntity;
import com.shanzmoo.db.job.entity.ScheduleJobLogEntity;
import com.shanzmoo.db.job.service.IScheduleJobLogService;
import com.shanzmoo.job.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;

/**
 *
 * 
 * @author： Gzhao 2021/2/9
 */
@Slf4j
public class BaseJob extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) {
        ScheduleJobEntity jobBean = (ScheduleJobEntity) context.getMergedJobDataMap().get(Constant.JOB_PARAM_KEY) ;
        IScheduleJobLogService scheduleJobLogService = SpringContextUtils.getBean(IScheduleJobLogService.class) ;
        // 定时器日志记录
        ScheduleJobLogEntity jobLog = new ScheduleJobLogEntity() ;
        jobLog.setJobId(jobBean.getJobId());
        jobLog.setBeanName(jobBean.getBeanName());
        jobLog.setParams(jobBean.getParams());
        jobLog.setMethodName(jobBean.getMethodName());
        long beginTime = System.currentTimeMillis() ;
        try {
            // 加载并执行定时器的 run 方法
            Object target = SpringContextUtils.getBean(jobBean.getBeanName());
            log.info(jobBean.getMethodName());
            String params = jobBean.getParams();
            Object obj;
            if (StrUtil.isEmpty(params)){
                Method method = target.getClass().getDeclaredMethod(jobBean.getMethodName());
                obj = method.invoke(target);
            } else {
                Method method = target.getClass().getDeclaredMethod(jobBean.getMethodName(), String.class);
                obj = method.invoke(target, params);
            }
            String result = "执行成功";
            if (null != obj && obj instanceof String){
                if (StrUtil.isNotBlank((String)obj)){
                    result = (String)obj;
                }
            }
            jobLog.setError(result);
            jobLog.setStatus(false);
        } catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());

            String errorMessage = ExceptionUtil.getRootCauseMessage(e);
            jobLog.setStatus(true);
            jobLog.setError(errorMessage);
        } finally {
            long executeTime = System.currentTimeMillis() - beginTime;
            jobLog.setTimes((int)executeTime);
            scheduleJobLogService.save(jobLog) ;
        }
    }
}
